package com.hbut.bili.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.hbut.bili.entity.Video;

@Repository
public class VideoDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 插入一条视频信息
	 * @param video
	 * @return
	 * @throws Exception
	 */
	public Integer inserVideo(Video video) throws Exception {
    	int rsInt = jdbcTemplate.update("INSERT INTO video (aid, bvid, cid, pic, title, descript, gmt_create, gmt_update) VALUES ('"+ video.getAid() +"', '" + video.getBvid() + "', '" + video.getCid() + "', '" + video.getPic() + "', '" + video.getTitle() + "', '" + video.getDescript() + "', now(), now() )");
    	return rsInt;
	}
	
	/**
	 * 获取视频信息列表
	 * @return
	 * @throws Exception 
	 */
	public List<Video> selectVideoList() throws Exception {
		List<Video> videoList = new ArrayList<Video>();
		videoList = jdbcTemplate.query("SELECT * FROM video", new VideoRowMapper());
		return videoList;
	}
	
	
	/**
	 * 根据主键获得一条视频信息
	 * @param aid
	 * @return
	 * @throws Exception
	 */
	public Video selectVideoById(Long aid) throws Exception {
		Video video = new Video();
		
		List<Video> videoList = jdbcTemplate.query("SELECT * FROM video WHERE aid=" + aid, new VideoRowMapper());
		if(videoList.size() > 0) {
			video = videoList.get(0);
		}
		return video;
	}
}

class VideoRowMapper implements RowMapper<Video> {
    @Override
    public Video mapRow(ResultSet rsVideo, int i) throws SQLException{
    	Video video = new Video();
    	video.setAid(rsVideo.getLong("aid"));
		video.setBvid(rsVideo.getString("bvid"));
		video.setCid(rsVideo.getString("cid"));
		video.setPic(rsVideo.getString("pic"));
		video.setTitle(rsVideo.getString("title"));
		video.setDescript(rsVideo.getString("descript"));
        return video;
    }
}
